﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Utils.Encryptor;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;

namespace DepartmentWork.Platform.Areas.SystemSettingArea.Controllers
{
    public class EmployeeController : BaseController
    {
        private IEnumerable<TEAMSPACE> teamspaces;

        public EmployeeController()
        {
            teamspaces = teamspaceRepository.GetModel().ToList();
        }

        // GET: SystemSettingArea/Employee
        public ActionResult Index(string flag = "", string flagInfo = "")
        {
            #region 校验用户是否登录

            if (CurrentUser.UserID == "")
            {
                return RedirectToAction("Login", "Home",
                    new { area = "", returnUrl = Request.Url.ToString() });
            }

            #endregion

            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;

            #region 校验身份

            ViewBag.IsAdmin = false;
            string[] pathArr = Request.Path.Split('/');
            Guid userGuid = new Guid(CurrentUser.UserID);
            USER_INFO userAdmin = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userAdmin.USER_ID).FirstOrDefault();
            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
            for (int i = 0; i < menuRole.Count(); i++)
            {
                int menuId = menuRole[i].MENU_ID;
                MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
                if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                {
                    ViewBag.IsAdmin = true;
                    break;
                }
            }
            #endregion

            #region 获取用户名及所有团队空间列表

            //获取用户名
            //ViewBag.UserName = System.Environment.UserName;

            //所有团队空间列表
            List<TeamSpaceViewModel> modelsOfTeamspace = (from item in teamspaces
                                                          select new TeamSpaceViewModel
                                                          {
                                                              TEAMSPACE_ID = item.TEAMSPACE_ID,
                                                              TEAMSPACE_NAME = item.TEAMSPACE_NAME
                                                          }).ToList();

            ViewBag.TeamspaceList = modelsOfTeamspace;

            #endregion

            Guid teamspaceGuid =
                teamspaceRepository.GetModel(r => r.TEAMSPACE_NAME == CurrentUser.Department)
                    .FirstOrDefault()
                    .TEAMSPACE_ID;
            List<USER_TEAMSAPCE> userTeams =
                userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamspaceGuid).ToList();

            List<UserInfoViewModel> model = new List<UserInfoViewModel>();

            List<USER_INFO> userList = new List<USER_INFO>();

            for (int i = 0; i < userTeams.Count; i++)
            {
                USER_INFO user = new USER_INFO();
                Guid userId = userTeams[i].USER_ID;
                user = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault();
                if (user.ENABLE != "2")
                {
                    userList.Add(user);
                }
            }

            if (userList.Count != 0)
            {
                model.AddRange(from item in userList
                               select new UserInfoViewModel()
                               {
                                   TeamspaceId = teamspaceGuid,
                                   UserId = item.USER_ID,
                                   DisplayName = item.DISPLAY_NAME
                               });
            }
            ViewBag.EmployeeCount = model.Count();

            Guid teamId = teamspaceRepository.GetModel(r => r.TEAMSPACE_NAME == CurrentUser.Department).FirstOrDefault().TEAMSPACE_ID;

            List<ROLE_INFO> roleList = roleRepository.GetModel(r => r.TEAMSPACE_ID == teamId&&r.STATUE==0).ToList();

            List<RoleViewModel> roleViewList = new List<RoleViewModel>();


            roleViewList.AddRange((from item in roleList
                                   select new RoleViewModel
                                   {
                                       DESCRIPTION = item.DESCRIPTION,
                                       ROLE_ID = item.ROLE_ID,
                                       ROLE_NAME = item.ROLE_NAME,
                                       STATUE = item.STATUE
                                   }).ToList());
            TempData["RoleList"] = roleViewList;
            return View(model);
        }


        [HttpPost]
        public JsonResult GetEmployeeInfo(Guid empId)
        {
            UserInfoViewModel model = new UserInfoViewModel();
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == empId).FirstOrDefault();
            model.UserId = user.USER_ID;
            model.UserName = user.LOGIN_NAME;
            model.DisplayName = user.DISPLAY_NAME;
            model.Enable = user.ENABLE;
            int roleId = userTeamsapceRepository.GetModel(r => r.USER_ID == empId).FirstOrDefault().ROLE_ID;
            model.UserRole = roleRepository.GetModel(r => r.ROLE_ID == roleId).FirstOrDefault().ROLE_ID.ToString();
            return this.Json(model);
        }


        [HttpPost]
        public ActionResult EditEmployee(FormCollection collection)
        {
            Guid userId = new Guid(collection["hid_EditEmployeeId"]);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault();

            user.DISPLAY_NAME = collection["tb_EditEmployeeDisplayName"].Trim() == ""
                ? user.DISPLAY_NAME
                : collection["tb_EditEmployeeDisplayName"].Trim();

            if (collection["ck_EditEmployeeStatus"] == "on")
            {
                user.ENABLE = "1";
            }
            else
            {
                user.ENABLE = "0";
            }
            string roleId = collection["ck_EditRoleId"];
            userRepository.Update(user);
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault();
            userTeam.ROLE_ID = Convert.ToInt32(roleId);
            userTeamsapceRepository.Update(userTeam);
            return this.RedirectToAction("Index", "Employee");
        }


        /// <summary>
        /// 激活用户
        /// </summary>
        /// <returns></returns>
        public ActionResult ActiveUser
            (Guid teamspaceId, string userId,string userDomainName,string userDisplay)
        {
            Guid userGuid = Guid.NewGuid();

            #region 判断当前用户是否已经激活

            USER_INFO userCheck = userRepository.GetModel
                (r => r.DISPLAY_NAME.Contains(userId)).FirstOrDefault();

            //if (userCheck.Count() != 0)
            //{
            //    return RedirectToAction("Login", new { flag = "False" });
            //}

            #endregion

            //未找到该用户
            if (userCheck == null || userCheck.LOGIN_NAME.Trim() == "")
            {
                #region 激活当前用户

                //在用户表中添加该用户
                USER_INFO user = new USER_INFO()
                {
                    DISPLAY_NAME = userDisplay == "" ? userId : userDisplay,
                    DOMAIN_NAME = userDomainName == "" ? null : userDomainName,
                    ENABLE = "1",
                    LOGIN_NAME = System.Environment.UserDomainName + @"\" + userId,
                    PASSWD = Utility.EncryptString("Bjhg8888",Utility.EncryptorType.SHA256),
                    USER_ID = userGuid
                };

                int roleId = roleRepository.GetModel(r => r.TEAMSPACE_ID == teamspaceId && r.ROLE_NAME == "普通用户")
                    .FirstOrDefault()
                    .ROLE_ID;

                //在用户-团队空间关系表中 添加记录
                USER_TEAMSAPCE userTeam = new USER_TEAMSAPCE()
                {
                    USER_TEAMSAPCE_ID = Guid.NewGuid(),
                    ROLE_ID = roleId,
                    TEAMSPACE_ID = teamspaceId,
                    USER_ID = userGuid
                };

                userRepository.Insert(user);
                userTeamsapceRepository.Insert(userTeam);

                #endregion
            }
            //找到 软删除用户
            else if (userCheck.ENABLE == "2")
            {
                userCheck.ENABLE = "1";
                userRepository.Update(userCheck);
            }
            else
            {
                return RedirectToAction("Index", new { flag = "False" });
            }

            return RedirectToAction("Index", new { flag = "Active" });
        }

        /// <summary>
        /// 软删除用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ActionResult DeleteUser(string userId)
        {
            Guid uid = new Guid(userId);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == uid).FirstOrDefault();
            user.ENABLE = "2";
            userRepository.Update(user);
            return RedirectToAction("Index");
        }

        [HttpPost]
        public JsonResult CheckUserPwd(string userId,string userPwd)
        {
            Guid uid=new Guid(userId);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == uid).FirstOrDefault();

            if (user.PASSWD!=Utility.EncryptString(userPwd,Utility.EncryptorType.SHA256))
            {
                return Json("false");
            }

            return Json("true");
        }

        [HttpPost]
        public ActionResult RenewPassword(FormCollection collection)
        {
            Guid userGuid = new Guid(collection["hid_EditUserId"]);

            USER_INFO model = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();

            string password = Utility.EncryptString(collection["tb_UserNewPassword"], Utility.EncryptorType.SHA256);

            model.PASSWD = password;

            userRepository.Update(model);

            return RedirectToAction("LogOut", "Home", new {area = ""});
        }

    }
}